<?php

declare(strict_types=1);

namespace app\controller\sys;

// 引入框架内置类
use think\facade\View;
use think\facade\Session;
use think\facade\Request;
use think\captcha\facade\Captcha;

use app\utils\ReUtils;
use app\model\SysUser;
use app\model\SysLoginFail;
use app\model\SysLoginNote;

/**
 * +----------------------------------------------------------------------
 * | 后台登录控制制器
 * +----------------------------------------------------------------------
 */
class Login
{
    // 登录页面
    public function index()
    {
        // 已登录自动跳转
        if (Session::has('adminuser')) {
            return redirect((string)url('/sys/index/index'));
        }
        $restore_url = Session::has('restore') ? Session::get('restore') : (string)url('index/index');

        View::assign('restore_url', $restore_url);

        return View::fetch();
    }

    // 处理登录
    public function dologin()
    {
        if (Request::isPost()) {
            $ip = Request::ip();
            $time = time();
            $datetime = date('Y-m-d H:i:s', $time);

            $username  = Request::param("username", '', 'strip_tags');
            $password  = Request::param("password", '', 'strip_tags');
            $verify = Request::param("verify", '', 'strip_tags');

            if (!$username || !$password || !$verify) {
                return ReUtils::error('用户名/密码/验证码不能为空');
            }

            if (false === Request::checkToken('__token__')) {
                return ReUtils::error('表单验证有误');
            }

            if (!Captcha::check($verify)) {
                // 验证失败
                return ReUtils::error('验证码不正确');
            }

            $info = SysUser::where('username', $username)->limit(1)->find();

            if (!$info) {
                SysLoginFail::saveFail($ip, $time);
                return ReUtils::error('用户名/密码不正确');
            }

            if (md5($password . $info->salt) != $info->password) {
                // 记录失败
                SysLoginFail::saveFail($ip, $time);

                SysLoginNote::record($info->userid, $info->username, $datetime, $ip, 1);

                return ReUtils::error('用户名/密码不正确');
            }

            if ($info->status == 1) {
                // 更新登录IP,登录时间和更新次数
                $perTime = $info->per_time;
                $perIp = $info->per_ip;

                $info->per_time = date('Y-m-d H:i:s', $time);
                $info->per_ip = $ip;
                $info->login_num += 1;

                $info->save();

                Session::set('adminuser', [
                    'userid'   => $info->userid,
                    'username' => $info->username,
                    'perTime'  => $perTime,
                    'perIp'    => $perIp,
                    'nickname' => $info->nickname,
                    'avatar'   => $info->avatar,
                    'loginNum' => $info->loginNum,
                    'roleid'   => $info->roleid
                ]);

                // 记录登录
                SysLoginNote::record($info->userid, $info->username, $datetime, $ip);

                return ReUtils::success('登录成功');
            } else {
                // 记录失败
                SysLoginNote::record($info->userid, $info->username, $datetime, $ip, 1);

                return ReUtils::error('用户已被禁用');
            }
        }
    }

    // 验证码
    public function verify()
    {
        return Captcha::create();
    }

    // 退出登录
    public function logout()
    {
        Session::delete('adminuser');
        return redirect((string) url('/sys/login/index'));
    }
}
